package com.wuwei.elearning.utils.word;

import com.wuwei.elearning.exception.ElearningMysqlException;
import com.wuwei.elearning.question.domain.Question;
import lombok.Data;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

@Data
@Component
public class QuestionToWord {


    @Value("${word.file.path}")
    private String wordPath;

    @Value("${word.template.path}")
    private String templatePath;


    public void writeToBeDocxForTable(List<Question> setQuestionList,String testType) {
        try {
            File file = new File(templatePath);
            if (!file.exists()) {
                throw new ElearningMysqlException(30011,"请检查模板文件是否存在！");
            }
            InputStream is = new FileInputStream(templatePath);
            XWPFDocument document = new XWPFDocument(is);
            //设置考卷信息
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            XWPFParagraph paragraph = paragraphs.get(1);
            String text = paragraph.getText();
            String replace = text.replace("${0}", testType);

            //这里如何用replace这个字符串替换text
            PoiUtils.replaceInParagraph(paragraph,text,replace);
            paragraph.getRuns().get(0).setBold(true);

            XWPFTable table = this.initTable(document, setQuestionList);
            setData(setQuestionList, document, table);

            //再次打开，检查里面的文本，准备删除之前的文本
            is = new FileInputStream(wordPath);
            document = new XWPFDocument(is);
            table = document.getTables().get(0);
            setDataAgain(table);
            //设置答案
            setAnswer(document,setQuestionList);

            //Save the document
            FileOutputStream outputStream1 = new FileOutputStream(wordPath);
            document.write(outputStream1);
            outputStream1.close();
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private XWPFTable initTable(XWPFDocument document,List<Question> setQuestionList) {
        int numCols = 2;
        XWPFTable table = document.createTable(setQuestionList.size()*6,numCols);
        table.setWidth("100%");

        // Set column widths (each column 50%)
        CTTblLayoutType tblLayout = table.getCTTbl().getTblPr().addNewTblLayout();
        tblLayout.setType(STTblLayoutType.FIXED);

        // Hide table borders
        setTableBorders(table);

        for (int col = 0; col < numCols; col++) {
            CTTblGridCol tblCol = table.getCTTbl().addNewTblGrid().addNewGridCol();
            tblCol.setW(BigInteger.valueOf(5000)); // Adjust the width as necessary
        }
        return table;
    }

    /**
     * 取消表格的边框
     * @param table
     */
    private void setTableBorders(XWPFTable table) {
        // 设置表格的边框为0，即隐藏所有边框
        CTTblBorders tblBorders = table.getCTTbl().getTblPr().addNewTblBorders();
        tblBorders.addNewBottom().setVal(STBorder.NONE);
        tblBorders.addNewTop().setVal(STBorder.NONE);
        tblBorders.addNewLeft().setVal(STBorder.NONE);
        tblBorders.addNewRight().setVal(STBorder.NONE);
        tblBorders.addNewInsideH().setVal(STBorder.NONE);
        tblBorders.addNewInsideV().setVal(STBorder.NONE);
    }

    /**
     * 设置答案
     * @param document
     * @param setQuestionList
     */
    private void setAnswer(XWPFDocument document, List<Question> setQuestionList) {
        document.createParagraph().createRun().setText("\n");

        String text =  "----------------------------------------------------------后面的为答案----------------------------------------------------------";
        document.createParagraph().createRun().setText(text);

        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < setQuestionList.size(); i++) {
            Question question = setQuestionList.get(i);
            String answer = question.getAnswer();
            builder.append(i+1+"."+answer+"   ");
        }
        document.createParagraph().createRun().setText(builder.toString());
    }


    /**
     * 再次打开word，删除一些行
     * @throws IOException
     */
    private void setDataAgain( XWPFTable table )  {

        List<XWPFTableRow> rows = table.getRows();

        List<Integer> removeRows = new ArrayList<>();
        for (int i = 0; i < rows.size(); i++) {
            XWPFTableRow row = rows.get(i);
            XWPFTableCell cell = row.getCell(0);
            String text = cell.getText();
            if (text.startsWith("B")||text.startsWith("D")) {
                XWPFTableCell lastCell = rows.get(i - 1).getCell(1);
                String lastText = lastCell.getText();
                if (lastText.equals(text)) {
                    //需要删除该行
                    removeRows.add(i);
                }
            }
        }
        int removeItems = 0;
        for (Integer removeRow : removeRows) {
            table.removeRow(removeRow+removeItems);
            removeItems--;
        }
    }

    /**
     * 第一次向表格添加数据
     * @param setQuestionList
     * @param document
     * @param table
     * @throws IOException
     */
    private void setData(List<Question> setQuestionList, XWPFDocument document, XWPFTable table) throws IOException {
        // Iterate through question list (example)
        for (int i = 0; i < setQuestionList.size(); i++) {
            Question question = setQuestionList.get(i);
            XWPFTableRow row = table.getRow(i * 6);
            row.getCell(0).setText((i+1)+"."+question.getQuestion());
            XWPFTableRow row1 = table.getRow(i * 6 + 1);
            row1.getCell(0).setText("A."+question.getItem1());
            XWPFTableRow row2 = table.getRow(i * 6 + 2);
            row2.getCell(0).setText("B."+question.getItem2());
            XWPFTableRow row3 = table.getRow(i * 6 + 3);
            row3.getCell(0).setText("C."+question.getItem3());
            XWPFTableRow row4 = table.getRow(i * 6 + 4);
            row4.getCell(0).setText("D."+question.getItem4());
            mergeCellsHorizontally(table,i*6,0,1);
            if (question.getItem1().length()>12||question.getItem2().length()>12||question.getItem3().length()>12||question.getItem4().length()>12) {
                mergeCellsHorizontally(table,i*6+1,0,1);
                mergeCellsHorizontally(table,i*6+2,0,1);
                mergeCellsHorizontally(table,i*6+3,0,1);
                mergeCellsHorizontally(table,i*6+4,0,1);
            } else {
                //这里要把单元格进行调整
                row1.getCell(1).setText("B."+question.getItem2());
                row3.getCell(1).setText("D."+question.getItem4());
            }
        }
        // Save the document
        FileOutputStream outputStream = new FileOutputStream(wordPath);
        document.write(outputStream);
        outputStream.close();
        document.close();
    }


    // 方法用于水平合并单元格
    public void mergeCellsHorizontally(XWPFTable table, int row, int fromCol, int toCol) {
        for (int colIndex = fromCol; colIndex <= toCol; colIndex++) {
            XWPFTableCell cell = table.getRow(row).getCell(colIndex);
            if ( colIndex == fromCol ) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

}
